<template>
  <div class="update-route-form">
    <a-form
      :model="editForm"
      :rules="editRules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="路线名称" name="routeName">
        <a-input v-model:value="editForm.routeName" placeholder="请输入路线名称" />
      </a-form-item>

      <a-form-item label="路线信息" name="routeInfo">
        <a-textarea v-model:value="editForm.routeInfo" placeholder="请输入路线详细信息" :rows="4" />
      </a-form-item>

      <a-form-item label="花费时间" name="spendTime">
        <a-input v-model:value="editForm.spendTime" placeholder="如：3-5天" />
      </a-form-item>

      <a-form-item label="适宜时间" name="suitableTime">
        <a-input v-model:value="editForm.suitableTime" placeholder="如：春季、夏季" />
      </a-form-item>

      <a-form-item label="沿途景点" name="alongScenics">
        <a-select
          v-model:value="editForm.alongScenics"
          mode="multiple"
          placeholder="请选择沿途景点"
          style="width: 100%"
          :loading="scenicsLoading"
          show-search
          :filter-option="false"
          @search="handleScenicSearch"
        >
          <a-select-option v-for="scenic in availableScenics" :key="scenic.id" :value="scenic.id">
            <div style="display: flex; align-items: center; gap: 8px">
              <img
                v-if="scenic.coverImage"
                :src="scenic.coverImage"
                :alt="scenic.scenicName"
                style="width: 24px; height: 24px; border-radius: 4px; object-fit: cover"
              />
              <span>{{ scenic.scenicName }}</span>
            </div>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="路线标签" name="routeTags">
        <a-select
          v-model:value="editForm.routeTags"
          mode="multiple"
          placeholder="请选择路线标签"
          style="width: 100%"
          :loading="tagsLoading"
        >
          <a-select-option v-for="tag in availableTags" :key="tag.id" :value="tag.tagName">
            {{ tag.tagName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <!-- 当前封面图片 -->
      <a-form-item label="当前封面图片" v-if="currentCoverImage">
        <div class="current-cover-image">
          <img
            :src="currentCoverImage"
            :alt="routeData.routeName"
            style="
              width: 200px;
              height: 150px;
              object-fit: cover;
              border-radius: 8px;
              border: 1px solid #d9d9d9;
            "
          />
          <div style="margin-top: 8px; color: #666; font-size: 12px">当前封面图片</div>
        </div>
      </a-form-item>

      <!-- 上传新封面图片 -->
      <a-form-item label="更新封面图片">
        <a-upload
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          list-type="picture-card"
          :max-count="1"
          accept="image/*"
          @change="handleUploadChange"
        >
          <div v-if="fileList.length < 1">
            <UploadOutlined />
            <div style="margin-top: 8px">上传新封面图片</div>
          </div>
        </a-upload>
        <div style="color: #666; font-size: 12px; margin-top: 4px">
          支持 JPG、PNG、WEBP 格式，文件大小不超过 2MB（可选，不上传则保持原图片）
        </div>
      </a-form-item>

      <!-- 操作按钮 -->
      <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
        <a-space>
          <a-button
            type="primary"
            @click="handleUpdate"
            :loading="updateLoading"
            :icon="h(SaveOutlined)"
          >
            保存修改
          </a-button>
          <a-button @click="handleCancel" :icon="h(CloseOutlined)"> 取消 </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadFile, UploadChangeParam } from 'ant-design-vue'
import { SaveOutlined, CloseOutlined, UploadOutlined } from '@ant-design/icons-vue'
import { updateRoute } from '@/api/routeController'
import { getListScenicVo } from '@/api/scenicController'
import { listTag } from '@/api/tagController'

// 定义 props 和 emits
interface Props {
  routeData: API.RouteVO
}

const props = defineProps<Props>()

const emit = defineEmits<{
  updated: [routeData: API.RouteVO, needRefresh?: boolean]
  cancel: []
}>()

const updateLoading = ref(false)
const scenicsLoading = ref(false)
const tagsLoading = ref(false)
const fileList = ref<UploadFile[]>([])
const availableScenics = ref<API.ScenicVO[]>([])
const availableTags = ref<API.TagVO[]>([])
const currentCoverImage = ref('')
const newCoverImageFile = ref<File | undefined>(undefined)

// 编辑表单数据
const editForm = reactive({
  id: undefined as number | undefined,
  routeName: '',
  routeInfo: '',
  spendTime: '',
  suitableTime: '',
  alongScenics: [] as number[],
  routeTags: [] as string[],
})

// 表单验证规则
const editRules = {
  routeName: [
    { required: true, message: '请输入路线名称', trigger: 'blur' },
    { min: 2, max: 50, message: '路线名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  routeInfo: [
    { required: true, message: '请输入路线信息', trigger: 'blur' },
    { min: 10, max: 1000, message: '路线信息长度在 10 到 1000 个字符', trigger: 'blur' },
  ],
  spendTime: [{ required: true, message: '请输入花费时间', trigger: 'blur' }],
  suitableTime: [{ required: true, message: '请输入适宜时间', trigger: 'blur' }],
  alongScenics: [
    { required: true, message: '请选择至少一个沿途景点', trigger: 'change' },
    { type: 'array', min: 1, message: '请选择至少一个沿途景点', trigger: 'change' },
  ],
}

// 初始化表单数据
const initializeForm = () => {
  if (!props.routeData.id) {
    message.error('路线 ID 无效，无法编辑')
    return
  }

  console.log('🔄 初始化编辑表单，路线数据:', props.routeData)

  editForm.id = props.routeData.id
  editForm.routeName = props.routeData.routeName || ''
  editForm.routeInfo = props.routeData.routeInfo || ''
  editForm.spendTime = props.routeData.spendTime || ''
  editForm.suitableTime = props.routeData.suitableTime || ''
  editForm.routeTags = [...(props.routeData.routeTags || [])]

  // 设置沿途景点ID数组 - 确保正确映射
  const scenicIds = (props.routeData.alongScenics || [])
    .map((scenic) => {
      if (typeof scenic === 'object' && scenic !== null && 'id' in scenic) {
        return scenic.id
      }
      // 如果直接是数字，则返回数字
      return typeof scenic === 'number' ? scenic : undefined
    })
    .filter((id): id is number => id !== undefined && !isNaN(id))

  editForm.alongScenics = scenicIds
  console.log('🗺️ 初始化沿途景点IDs:', scenicIds)

  // 设置当前封面图片
  currentCoverImage.value = props.routeData.routeCoverImage || ''

  // 重置文件上传
  fileList.value = []
  newCoverImageFile.value = undefined

  console.log('✅ 表单初始化完成:', editForm)
}

// 获取景点列表
const getAvailableScenics = async (searchValue = '') => {
  try {
    scenicsLoading.value = true
    console.log('🔍 获取景点列表，搜索值:', searchValue)
    const res = await getListScenicVo({
      scenicName: searchValue || undefined,
      pageSize: 50, // 获取更多景点用于选择
    })
    console.log('📡 景点列表响应:', res)
    if (res.data.code === 200 && res.data.data) {
      availableScenics.value = res.data.data.records ?? []
      console.log('✅ 获取到景点列表:', availableScenics.value.length, '个景点')
    } else {
      console.warn('⚠️ 获取景点列表失败:', res.data.message)
    }
  } catch (error) {
    console.error('❌ 获取景点列表失败:', error)
    message.error('获取景点列表失败')
  } finally {
    scenicsLoading.value = false
  }
}

// 获取标签列表
const getAvailableTags = async () => {
  try {
    tagsLoading.value = true
    console.log('🔍 获取标签列表')
    const res = await listTag({})
    const responseData = res as { data: API.BaseResponseListTagVO }
    console.log('📡 标签列表响应:', responseData)
    if (responseData.data?.code === 200 && responseData.data?.data) {
      availableTags.value = responseData.data.data ?? []
      console.log('✅ 获取到标签列表:', availableTags.value.length, '个标签')
    } else {
      console.warn('⚠️ 获取标签列表失败:', responseData.data?.message)
    }
  } catch (error) {
    console.error('❌ 获取标签列表失败:', error)
    message.error('获取标签列表失败')
  } finally {
    tagsLoading.value = false
  }
}

// 搜索景点
const handleScenicSearch = (value: string) => {
  getAvailableScenics(value)
}

// 图片上传前的验证
const beforeUpload = (file: UploadFile) => {
  console.log('📋 图片上传前验证:', {
    name: file.name,
    size: file.size,
    type: file.type,
    uid: file.uid,
  })

  const isJpgOrPng =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG/WEBP 格式的图片!')
    console.error('❌ 图片格式不支持:', file.type)
    return false
  }
  const isLt2M = (file.size || 0) / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    console.error('❌ 图片过大:', (file.size || 0) / 1024 / 1024, 'MB')
    return false
  }

  console.log('✅ 图片验证通过')
  return false // 阻止自动上传，我们手动处理
}

// 图片上传变化处理
const handleUploadChange = (info: UploadChangeParam) => {
  console.log('📷 图片上传变化详情:', {
    file: info.file,
    fileList: info.fileList,
    fileStatus: info.file.status,
    hasOriginFileObj: !!info.file.originFileObj,
  })

  if (info.file.status === 'removed') {
    newCoverImageFile.value = undefined
    console.log('🗑️ 移除图片文件')
    return
  }

  // 检查是否有原始文件对象
  if (info.file.originFileObj) {
    newCoverImageFile.value = info.file.originFileObj
    console.log('✅ 设置新的路线封面图片:', {
      name: info.file.name,
      size: info.file.size,
      type: info.file.type,
      isFile: info.file.originFileObj instanceof File,
      originFileObj: info.file.originFileObj,
    })
  } else if (info.file.status === 'done' || !info.file.status) {
    // 如果没有 originFileObj，尝试使用 file 本身
    const fileObj = info.file as unknown as File
    if (fileObj instanceof File) {
      newCoverImageFile.value = fileObj
      console.log('✅ 使用文件对象本身:', {
        name: fileObj.name,
        size: fileObj.size,
        type: fileObj.type,
        isFile: fileObj instanceof File,
      })
    } else {
      console.warn('⚠️ 无法获取有效的文件对象:', info.file)
    }
  }

  fileList.value = [...info.fileList]
  console.log('📋 当前文件列表:', fileList.value.length, '个文件')
  console.log('📂 newCoverImageFile 最终状态:', {
    hasFile: !!newCoverImageFile.value,
    file: newCoverImageFile.value,
  })
}

// 处理更新
const handleUpdate = async () => {
  updateLoading.value = true

  try {
    // ===== 详细的调试信息开始 =====
    console.log('🚀 === 开始路线更新流程 ===')
    console.log('📝 表单数据:', editForm)
    console.log('📋 文件列表状态:', {
      fileListLength: fileList.value.length,
      fileList: fileList.value.map((f) => ({
        uid: f.uid,
        name: f.name,
        status: f.status,
        hasOriginFileObj: !!f.originFileObj,
      })),
    })
    console.log('🖼️ 新封面图片文件详情:', {
      file: newCoverImageFile.value,
      hasFile: !!newCoverImageFile.value,
      fileName: newCoverImageFile.value?.name,
      fileSize: newCoverImageFile.value?.size,
      fileType: newCoverImageFile.value?.type,
      isFile: newCoverImageFile.value instanceof File,
    })

    // 额外验证
    if (newCoverImageFile.value) {
      console.log('✅ 文件验证通过 - 准备上传图片')
      console.log('📸 图片文件完整信息:', {
        constructor: newCoverImageFile.value.constructor.name,
        lastModified: newCoverImageFile.value.lastModified,
        webkitRelativePath:
          (newCoverImageFile.value as File & { webkitRelativePath?: string }).webkitRelativePath ||
          'N/A',
      })
    } else {
      console.log('⚠️ 没有检测到新的图片文件')
    }
    // ===== 详细的调试信息结束 =====

    // 验证必填字段
    if (!editForm.routeName || editForm.routeName.trim() === '') {
      message.error('路线名称不能为空')
      return
    }

    if (!editForm.routeInfo || editForm.routeInfo.trim() === '') {
      message.error('路线信息不能为空')
      return
    }

    if (!editForm.alongScenics || editForm.alongScenics.length === 0) {
      message.error('请选择至少一个沿途景点')
      return
    }

    console.log('📝 开始更新路线，表单数据:', editForm)
    console.log('🖼️ 新封面图片文件详情:', {
      file: newCoverImageFile.value,
      hasFile: !!newCoverImageFile.value,
      fileName: newCoverImageFile.value?.name,
      fileSize: newCoverImageFile.value?.size,
      fileType: newCoverImageFile.value?.type,
      isFile: newCoverImageFile.value instanceof File,
    })
    console.log('📋 文件列表状态:', {
      fileListLength: fileList.value.length,
      fileList: fileList.value,
    })

    const updateParams: API.updateRouteParams = {
      id: editForm.id,
      routeName: editForm.routeName.trim(),
      routeInfo: editForm.routeInfo.trim(),
      spendTime: editForm.spendTime || '',
      suitableTime: editForm.suitableTime || '',
      alongScenics: [...editForm.alongScenics], // 确保传递数组副本
      routeTags: [...editForm.routeTags], // 确保传递数组副本
      routeCoverImage: newCoverImageFile.value, // 只有新图片才传递
    }

    console.log('🚀 发送更新路线参数详情:', {
      ...updateParams,
      routeCoverImage: updateParams.routeCoverImage
        ? {
            name: updateParams.routeCoverImage.name,
            size: updateParams.routeCoverImage.size,
            type: updateParams.routeCoverImage.type,
            isFile: updateParams.routeCoverImage instanceof File,
          }
        : null,
    })

    const response = await updateRoute(updateParams)

    console.log('📡 更新路线响应:', response)

    if (response.data.code === 200) {
      message.success('路线更新成功！')

      // 构建更新后的路线数据 - 需要重新获取景点详情
      const updatedAlongScenics = availableScenics.value.filter((scenic) =>
        editForm.alongScenics.includes(scenic.id!),
      )

      // 处理封面图片URL
      let updatedCoverImage = props.routeData.routeCoverImage
      let tempUrl: string | null = null

      if (newCoverImageFile.value) {
        // 由于后端更新接口只返回Boolean，无法获取新的图片URL
        // 我们创建临时的本地URL用于预览，并提示用户刷新页面
        tempUrl = URL.createObjectURL(newCoverImageFile.value)
        updatedCoverImage = tempUrl
        console.log('🖼️ 使用临时图片URL:', updatedCoverImage)

        // 提示用户刷新页面以看到最新图片
        message.info('图片已更新成功！刷新页面可查看最新图片', 3)
      }

      const updatedRouteData: API.RouteVO = {
        ...props.routeData,
        routeName: updateParams.routeName!,
        routeInfo: updateParams.routeInfo!,
        spendTime: updateParams.spendTime!,
        suitableTime: updateParams.suitableTime!,
        routeTags: [...updateParams.routeTags!],
        alongScenics: updatedAlongScenics,
        routeCoverImage: updatedCoverImage,
        updateTime: new Date().toISOString(),
      }

      console.log('✅ 构建更新后的路线数据:', updatedRouteData)

      // 如果上传了新图片，清理临时URL避免内存泄漏
      if (tempUrl) {
        setTimeout(() => {
          URL.revokeObjectURL(tempUrl!)
        }, 10000) // 10秒后清理
      }

      // 如果上传了新图片，建议父组件刷新数据
      emit('updated', updatedRouteData, !!newCoverImageFile.value)
    } else {
      message.error('更新失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 更新路线请求失败:', error)
    message.error('更新失败，请稍后再试')
  } finally {
    updateLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 监听 routeData 变化，重新初始化表单
watch(
  () => props.routeData,
  () => {
    initializeForm()
  },
  { immediate: true, deep: true },
)

// 组件挂载时获取数据
onMounted(() => {
  getAvailableScenics()
  getAvailableTags()

  // 添加调试信息
  console.log('🔧 UpdateRouteForm 组件已挂载')
  console.log('📁 初始文件状态:', {
    fileList: fileList.value,
    newCoverImageFile: newCoverImageFile.value,
    currentCoverImage: currentCoverImage.value,
  })
})
</script>

<style scoped>
.update-route-form {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.current-cover-image {
  text-align: center;
}

.ant-upload-select-picture-card {
  width: 104px;
  height: 104px;
}

:deep(.ant-select-selection-item) {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
